<template>
  <div class="exception-tracking">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>异常追踪处理</h2>
    </div>

    <!-- 异常列表 -->
    <div class="exception-list">
      <div class="list-header">
        <div class="header-left">
          <span class="list-title">异常列表</span>
          <el-tag class="total-tag" type="info" effect="plain">总计: {{ exceptionTotal }}</el-tag>
        </div>
        <div class="header-right">
          <el-button type="primary" size="small" @click="handleAddException">
            <el-icon><Plus /></el-icon>
            新增异常
          </el-button>
          <!-- <el-button type="success" size="small" @click="handleExportExcel">
            <el-icon><Download /></el-icon>
            导出Excel
          </el-button> -->
        </div>
      </div>

      <!-- 搜索和筛选 -->
      <div class="search-filter">
        <el-form :inline="true" :model="exceptionQueryForm" class="filter-form">
          <el-form-item label="异常类型" >
            <el-select v-model="exceptionQueryForm.processType" placeholder="全部类型" clearable filterable>
              <el-option label="点胶异常" value="点胶异常" />
              <el-option label="色彩异常" value="色彩异常" />
              <el-option label="规格异常" value="规格异常" />
              <el-option label="其他异常" value="其他异常" />
            </el-select>
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="exceptionQueryForm.currentStatus" placeholder="全部状态" clearable filterable>
              <el-option label="待处理" value="待处理" />
              <el-option label="进行中" value="进行中" />
              <el-option label="已完成" value="已完成" />
            </el-select>
          </el-form-item>
          <el-form-item label="关键词">
            <el-input v-model="exceptionQueryForm.keyword" placeholder="编号/报告人" clearable />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="searchExceptions">搜索</el-button>
            <el-button @click="resetExceptionQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 表格 -->
      <el-table 
        :data="exceptionList" 
        style="width: 100%" 
        v-loading="exceptionLoading"
        border
        stripe
        highlight-current-row
        @row-click="handleRowClick"
      >
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="processType" label="异常类型" width="120" />
        <el-table-column prop="exceptionNumber" label="异常编号" width="150" show-overflow-tooltip />
        <el-table-column prop="reporter" label="报告人" width="100" />
        <el-table-column prop="reportTime" label="报告时间" width="150" sortable />
        <el-table-column prop="currentStatus" label="当前状态" width="120">
          <template #default="{ row }">
            <el-tag :type="getStatusTagType(row.currentStatus)">{{ row.currentStatus }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="priority" label="优先级" width="100">
          <template #default="{ row }">
            <el-tag 
              :type="row.priority === '高' ? 'danger' : row.priority === '中' ? 'warning' : 'info'"
              effect="dark"
              size="small"
            >
              {{ row.priority }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="异常描述" min-width="150" show-overflow-tooltip />
        <el-table-column label="操作" width="220" fixed="right">
          <template #default="{ row }">
            <el-button size="small" type="primary" @click="handleView(row)">
              <el-icon><View /></el-icon> 详情
            </el-button>
            <el-button size="small" type="success" @click="handleProcess(row)" :disabled="row.currentStatus === '已完成'">
              <el-icon><Edit /></el-icon> 处理
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="exceptionQueryForm.pageNumber"
          v-model:page-size="exceptionQueryForm.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="exceptionTotal"
          @size-change="handleExceptionSizeChange"
          @current-change="handleExceptionCurrentChange"
          background
        />
      </div>
    </div>

    <!-- 新增异常弹窗 -->
    <el-dialog v-model="addDialogVisible" title="新增异常" width="500px" :close-on-click-modal="false">
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="90px">
        <el-form-item label="异常类型" prop="processType">
          <el-select v-model="addForm.processType" placeholder="请选择异常类型">
            <el-option label="点胶异常" value="点胶异常" />
            <el-option label="色彩异常" value="色彩异常" />
            <el-option label="规格异常" value="规格异常" />
            <el-option label="其他异常" value="其他异常" />
          </el-select>
        </el-form-item>
        <el-form-item label="报告人" prop="reporter">
          <el-input v-model="addForm.reporter" placeholder="请输入报告人" />
        </el-form-item>
        <el-form-item label="报告时间" prop="reportTime">
          <el-date-picker v-model="addForm.reportTime" type="date" placeholder="选择日期" format="YYYY-MM-DD" value-format="YYYY-MM-DD" />
        </el-form-item>
        <el-form-item label="优先级" prop="priority">
          <el-select v-model="addForm.priority" placeholder="请选择优先级">
            <el-option label="高" value="高" />
            <el-option label="中" value="中" />
            <el-option label="低" value="低" />
          </el-select>
        </el-form-item>
        <el-form-item label="异常ID" prop="inspectionId">
          <el-select v-model="addForm.inspectionId" placeholder="请选择异常ID" :loading="inspectionLoading" filterable>
            <el-option 
              v-for="id in unqualifiedInspectionList" 
              :key="id" 
              :label="id" 
              :value="id" 
            />
          </el-select>
        </el-form-item>
        <el-form-item label="异常描述" prop="description">
          <el-input v-model="addForm.description" type="textarea" placeholder="请输入异常描述" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="addDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitAddException">提交</el-button>
      </template>
    </el-dialog>

    <!-- 异常详情弹窗 -->
    <el-dialog v-model="detailDialogVisible" title="异常详情" width="500px" :close-on-click-modal="false">
      <el-descriptions :column="1" border>
        <el-descriptions-item label="异常编号">{{ exceptionDetail.exceptionNumber }}</el-descriptions-item>
        <el-descriptions-item label="异常类型">{{ exceptionDetail.processType }}</el-descriptions-item>
        <el-descriptions-item label="异常ID">{{ exceptionDetail.inspectionId }}</el-descriptions-item>
        <el-descriptions-item label="报告人">{{ exceptionDetail.reporter }}</el-descriptions-item>
        <el-descriptions-item label="报告时间">{{ exceptionDetail.reportTime }}</el-descriptions-item>
        <el-descriptions-item label="当前状态">{{ exceptionDetail.currentStatus }}</el-descriptions-item>
        <el-descriptions-item label="优先级">{{ exceptionDetail.priority }}</el-descriptions-item>
        <el-descriptions-item label="异常描述">{{ exceptionDetail.description }}</el-descriptions-item>
        <el-descriptions-item label="处理结果" v-if="exceptionDetail.result">{{ exceptionDetail.result }}</el-descriptions-item>
        <el-descriptions-item label="处理人" v-if="exceptionDetail.handler">{{ exceptionDetail.handler }}</el-descriptions-item>
        <el-descriptions-item label="处理时间" v-if="exceptionDetail.handleTime">{{ exceptionDetail.handleTime }}</el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <div class="dialog-footer-flex">
          <div class="dialog-footer-left">
            <el-button type="primary" @click="handleTrackFromDetail">跟踪记录</el-button>
          </div>
          <div class="dialog-footer-right">
            <el-button @click="detailDialogVisible = false">关闭</el-button>
          </div>
        </div>
      </template>
    </el-dialog>

    <!-- 异常处理弹窗 -->
    <el-dialog v-model="processDialogVisible" title="异常处理" width="600px" :close-on-click-modal="false">
      <el-form :model="processForm" :rules="processFormRules" ref="processFormRef" label-width="110px">
        <el-form-item label="异常编号">
          <el-input v-model="processForm.exceptionNumber" disabled />
        </el-form-item>
        <el-form-item label="异常类型">
          <el-input :value="processForm.trackingCategory || processForm.processType" disabled />
        </el-form-item>
        <el-form-item label="异常ID">
          <el-input v-model="processForm.inspectionId" disabled />
        </el-form-item>
        <el-form-item label="报告人">
          <el-input v-model="processForm.reporter" disabled />
        </el-form-item>
        <el-form-item label="报告时间">
          <el-input v-model="processForm.reportTime" disabled />
        </el-form-item>
        <el-form-item label="异常描述">
          <el-input v-model="processForm.description" type="textarea" disabled />
        </el-form-item>
        <el-form-item label="异常状态" prop="status">
          <el-select v-model="processForm.status" placeholder="请选择异常状态">
            <el-option label="待处理" value="待处理" />
            <el-option label="进行中" value="进行中" />
            <el-option label="已完成" value="已完成" />
          </el-select>
        </el-form-item>
        <el-form-item label="处理意见" prop="processComment">
          <el-input v-model="processForm.processComment" type="textarea" placeholder="请输入处理意见" />
        </el-form-item>
        <el-form-item label="处理结果" prop="processResult">
          <el-input v-model="processForm.processResult" type="textarea" placeholder="请输入处理结果" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="processDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitProcessException">提交</el-button>
      </template>
    </el-dialog>

    <!-- 跟踪记录时间线弹窗 -->
    <el-dialog v-model="timelineDialogVisible" title="异常跟踪记录" width="800px" :close-on-click-modal="false">
      <div v-loading="timelineLoading">
        <el-timeline v-if="timelineData.length > 0">
          <el-timeline-item
            v-for="(item, index) in timelineData"
            :key="index"
            :timestamp="item.timestamp"
            :type="item.type"
            :color="item.color"
            :icon="item.icon"
            placement="top"
          >
            <el-card class="timeline-card">
              <div class="timeline-header">
                <h4>{{ item.title }}</h4>
                <el-tag :type="item.tagType" size="small">{{ item.stage }}</el-tag>
              </div>
              <div class="timeline-content">
                <el-descriptions :column="2" size="small" border>
                  <el-descriptions-item 
                    v-for="(detail, key) in item.details" 
                    :key="key" 
                    :label="detail.label"
                  >
                    {{ detail.value }}
                  </el-descriptions-item>
                </el-descriptions>
              </div>
              <div class="timeline-footer" v-if="item.remark">
                <p class="remark">{{ item.remark }}</p>
              </div>
            </el-card>
          </el-timeline-item>
        </el-timeline>
        <el-empty v-else description="暂无跟踪记录" />
      </div>
      <template #footer>
        <el-button @click="timelineDialogVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick, reactive, computed } from 'vue'
import * as echarts from 'echarts'
import { Plus, Download, View, Edit, More, Warning, Close } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  getExceptionListService,
  addExceptionTrackingService,
  updateExceptionTrackingService,
  getExceptionDetailService,
  getExceptionTrackingService,
  listUnqualifiedInspectionService,
  getExceptionTrackingTimelineService
} from '@/api/QualityManager'

// 日期格式化工具函数
const formatDate = (date: Date, format: string): string => {
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0') 
  const seconds = String(date.getSeconds()).padStart(2, '0')

  return format
    .replace('YYYY', String(year))
    .replace('MM', month)
    .replace('DD', day)
    .replace('HH', hours)
    .replace('mm', minutes)
    .replace('ss', seconds)
}

// 图表引用
const processChart = ref()
const costPieChart = ref()
const costTrendChart = ref()
let processChartInstance: echarts.ECharts | null = null
let costPieChartInstance: echarts.ECharts | null = null
let costTrendChartInstance: echarts.ECharts | null = null

// 异常列表数据
const exceptionLoading = ref(false)
const exceptionList = ref<any[]>([])
const exceptionTotal = ref(0)
const exceptionQueryForm = reactive({
  pageNumber: 1,
  pageSize: 10,
  processType: '',
  currentStatus: '',
  dateRange: [],
  keyword: ''
})

// 质量成本数据
const costLoading = ref(false)

// 统计数据
const statsData = ref([
  {
    category: '原材料浪费',
    cost: '¥25,680',
    lastCost: '¥22,830',
    growthRate: '↑12.5%',
    proportion: '33.3',
    description: '设备资料不齐，材料价格增长导致'
  },
  {
    category: '返工成本',
    cost: '¥18,450',
    lastCost: '¥17,540',
    growthRate: '↑5.2%',
    proportion: '23.9',
    description: '工艺参数优化，运工效率提升'
  },
  {
    category: '报废损失',
    cost: '¥32,960',
    lastCost: '¥30,320',
    growthRate: '↑8.7%',
    proportion: '42.8',
    description: '供应商材料质量波动，成品合格率下降'
  }
])

// 新增异常弹窗控制与表单
const addDialogVisible = ref(false)
const addForm = reactive({
  processType: '',
  exceptionNumber: '',
  reporter: '',
  reportTime: '',
  currentStatus: '待处理',
  priority: '',
  description: '',
  inspectionId: '' // 新增异常ID字段
})
const addFormRef = ref()
const addFormRules = {
  processType: [{ required: true, message: '请选择异常类型', trigger: 'change' }],
  reporter: [{ required: true, message: '请输入报告人', trigger: 'blur' }],
  reportTime: [{ required: true, message: '请选择报告时间', trigger: 'change' }],
  priority: [{ required: true, message: '请选择优先级', trigger: 'change' }],
  description: [{ required: true, message: '请输入异常描述', trigger: 'blur' }],
  inspectionId: [{ required: true, message: '请选择异常ID', trigger: 'change' }]
}

// 不合格质检列表
const unqualifiedInspectionList = ref<number[]>([])
const inspectionLoading = ref(false)

// 异常详情弹窗控制与数据
const detailDialogVisible = ref(false)
const exceptionDetail = ref<any>({})

// 异常处理弹窗控制与表单
const processDialogVisible = ref(false)
const processForm = reactive<any>({})
const processFormRef = ref()
const processFormRules = {
  status: [{ required: true, message: '请选择异常状态', trigger: 'change' }],
  processComment: [{ required: true, message: '请输入处理意见', trigger: 'blur' }],
  processResult: [{ required: true, message: '请输入处理结果', trigger: 'blur' }]
}

// 跟踪记录时间线弹窗控制与数据
const timelineDialogVisible = ref(false)
const timelineData = ref<any[]>([])
const timelineLoading = ref(false)

// 初始化流程图表
const initProcessChart = async () => {
  await nextTick()
  if (processChart.value) {
    processChartInstance = echarts.init(processChart.value)
    const option = {
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'cross'
        }
      },
      legend: {
        data: ['原材料浪费', '报废损失', '返工成本'],
        top: 20
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: ['1月', '2月', '3月', '4月', '5月', '6月'],
        axisLabel: {
          fontSize: 12
        }
      },
      yAxis: {
        type: 'value',
        axisLabel: {
          formatter: function(value: number) {
            if (value >= 1000) {
              return (value / 1000).toFixed(0) + 'k'
            }
            return value.toString()
          },
          fontSize: 12
        }
      },
      series: [
        {
          name: '原材料浪费',
          type: 'line',
          data: [15000, 18000, 20000, 23000, 25000, 30000],
          smooth: true,
          lineStyle: {
            color: '#1890ff',
            width: 3
          },
          itemStyle: {
            color: '#1890ff'
          },
          symbol: 'circle',
          symbolSize: 6
        },
        {
          name: '报废损失',
          type: 'line',
          data: [25000, 28000, 29000, 29500, 30000, 30500],
          smooth: true,
          lineStyle: {
            color: '#52c41a',
            width: 3
          },
          itemStyle: {
            color: '#52c41a'
          },
          symbol: 'circle',
          symbolSize: 6
        },
        {
          name: '返工成本',
          type: 'line',
          data: [22000, 20000, 18000, 16000, 15000, 14000],
          smooth: true,
          lineStyle: {
            color: '#f5222d',
            width: 3
          },
          itemStyle: {
            color: '#f5222d'
          },
          symbol: 'circle',
          symbolSize: 6
        }
      ]
    }
    processChartInstance.setOption(option)
  }
}

// 初始化成本饼图
const initCostPieChart = async () => {
  await nextTick()
  if (costPieChart.value) {
    costPieChartInstance = echarts.init(costPieChart.value)
    const option = {
      tooltip: {
        trigger: 'item',
        formatter: '{a} <br/>{b}: {c} ({d}%)'  
      },
      legend: {
        orient: 'vertical',
        right: 10,
        top: 'center',
        data: statsData.value.map(item => item.category)
      },
      series: [
        {
          name: '成本占比',
          type: 'pie',
          radius: ['50%', '70%'],
          avoidLabelOverlap: false,
          itemStyle: {
            borderRadius: 10,
            borderColor: '#fff',
            borderWidth: 2
          },
          label: {
            show: false,
            position: 'center'
          },
          emphasis: {
            label: {
              show: true,
              fontSize: 16,
              fontWeight: 'bold'
            }
          },
          labelLine: {
            show: false
          },
          data: statsData.value.map(item => ({
            name: item.category,
            value: parseFloat(item.proportion)
          }))
        }
      ]
    }
    costPieChartInstance.setOption(option)
  }
}

// 初始化成本趋势图
const initCostTrendChart = async () => {
  await nextTick()
  if (costTrendChart.value) {
    costTrendChartInstance = echarts.init(costTrendChart.value)
    const option = {
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        }
      },
      legend: {
        data: ['原材料浪费', '返工成本', '报废损失'],
        top: 10
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '3%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: ['1月', '2月', '3月', '4月', '5月', '6月']
      },
      yAxis: {
        type: 'value',
        name: '金额 (元)',
        axisLabel: {
          formatter: function(value: number) {
            if (value >= 10000) {
              return (value / 10000).toFixed(1) + '万'
            }
            return value.toString()
          }
        }
      },
      series: [
        {
          name: '原材料浪费',
          type: 'bar',
          stack: 'total',
          emphasis: {
            focus: 'series'
          },
          data: [12000, 15000, 18000, 20000, 22000, 25000],
          itemStyle: {
            color: '#1890ff'
          }
        },
        {
          name: '返工成本',
          type: 'bar',
          stack: 'total',
          emphasis: {
            focus: 'series'
          },
          data: [18000, 17000, 16000, 15000, 14000, 13000],
          itemStyle: {
            color: '#f5222d'
          }
        },
        {
          name: '报废损失',
          type: 'bar',
          stack: 'total',
          emphasis: {
            focus: 'series'
          },
          data: [25000, 26000, 27000, 28000, 30000, 32000],
          itemStyle: {
            color: '#52c41a'
          }
        }
      ]
    }
    costTrendChartInstance.setOption(option)
  }
}

// 获取状态标签类型
const getStatusTagType = (status: string) => {
  switch (status) {
    case '进行中':
      return 'primary'
    case '待处理':
      return 'warning'
    case '已完成':
      return 'success'
    default:
      return 'info'
  }
}

// 异常列表方法
const searchExceptions = async () => {
  exceptionLoading.value = true
  try {
    const params = {
      ...exceptionQueryForm,
      pageNum: exceptionQueryForm.pageNumber,
      pageSize: exceptionQueryForm.pageSize,
      trackingCategory: exceptionQueryForm.processType,
      status: exceptionQueryForm.currentStatus
    }
    const res = await getExceptionListService(params)
    exceptionList.value = res.data.records || []
    exceptionTotal.value = res.data.total || 0
  } catch (e) {
    ElMessage.error('获取异常列表失败')
  } finally {
    exceptionLoading.value = false
  }
}

const resetExceptionQuery = () => {
  exceptionQueryForm.processType = ''
  exceptionQueryForm.currentStatus = ''
  exceptionQueryForm.dateRange = []
  exceptionQueryForm.keyword = ''
  searchExceptions()
}

const handleExceptionSizeChange = (size: number) => {
  exceptionQueryForm.pageSize = size
  searchExceptions()
}

const handleExceptionCurrentChange = (page: number) => {
  exceptionQueryForm.pageNumber = page
  searchExceptions()
}

const handleRowClick = (row: any) => {
  console.log('行点击:', row)
}

// 获取不合格质检列表
const getUnqualifiedInspectionList = async () => {
  inspectionLoading.value = true
  try {
    const res = await listUnqualifiedInspectionService()
    unqualifiedInspectionList.value = res.data || []
  } catch (e) {
    ElMessage.error('获取不合格质检列表失败')
  } finally {
    inspectionLoading.value = false
  }
}

const handleAddException = () => {
  addDialogVisible.value = true
  // 重置表单
  Object.assign(addForm, {
    processType: '',
    exceptionNumber: '',
    reporter: '',
    reportTime: '',
    currentStatus: '待处理',
    priority: '',
    description: '',
    inspectionId: ''
  })
  // 获取不合格质检列表
  getUnqualifiedInspectionList()
}

// 获取异常跟踪时间线
const getExceptionTimeline = async (exceptionNumber: string) => {
  timelineLoading.value = true
  try {
    const res = await getExceptionTrackingTimelineService(exceptionNumber)
    timelineData.value = res.data || []
  } catch (e) {
    ElMessage.error('获取跟踪记录失败')
  } finally {
    timelineLoading.value = false
  }
}

const handleTrack = async (row: any) => {
  timelineDialogVisible.value = true
  await getExceptionTimeline(row.exceptionNumber)
}

// 从详情页打开跟踪记录
const handleTrackFromDetail = async () => {
  await getExceptionTimeline(exceptionDetail.value.exceptionNumber)
  timelineDialogVisible.value = true
}

const handleCopy = (row: any) => {
  // 模拟复制到剪贴板
  ElMessage.success(`已复制 ${row.exceptionNumber} 信息到剪贴板`)
}

const handleDelete = (row: any) => {
  ElMessageBox.confirm(
    `确定要删除异常 ${row.exceptionNumber} 吗？`,
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    ElMessage.success(`异常 ${row.exceptionNumber} 已删除`)
  }).catch(() => {
    // 取消删除
  })
}

// 查看详情
const handleView = async (row: any) => {
  try {
    const res = await getExceptionDetailService(row.exceptionNumber)
    exceptionDetail.value = res.data || {}
    detailDialogVisible.value = true
  } catch (e) {
    ElMessage.error('获取异常详情失败')
  }
}

// 处理异常
const handleProcess = async (row: any) => {
  try {
    const res = await getExceptionDetailService(row.exceptionNumber)
    Object.assign(processForm, res.data || {})
    processDialogVisible.value = true
  } catch (e) {
    ElMessage.error('获取异常详情失败')
  }
}

const submitAddException = () => {
  addFormRef.value.validate(async (valid: boolean) => {
    if (!valid) return
    try {
      const payload = { ...addForm }
      // 生成异常编号
      payload.exceptionNumber = 'BT' + new Date().getFullYear() + Math.floor(Math.random() * 100000)
      // 补全 reportTime
      if (payload.reportTime && payload.reportTime.length === 10) {
        payload.reportTime = payload.reportTime + ' 00:00'
      }
      // 字段映射
      payload.processType = payload.processType
      payload.currentStatus = '待处理'
      const res = await addExceptionTrackingService(payload)
      ElMessage.success('新增异常成功')
      addDialogVisible.value = false
      searchExceptions()
    } catch (e) {
      ElMessage.error('新增异常失败')
    }
  })
}

const submitProcessException = () => {
  processFormRef.value.validate(async (valid: boolean) => {
    if (!valid) return
    try {
      const payload = { ...processForm }
      await updateExceptionTrackingService(payload)
      ElMessage.success('异常处理成功')
      processDialogVisible.value = false
      searchExceptions()
    } catch (e) {
      ElMessage.error('异常处理失败')
    }
  })
}

// 组件挂载
onMounted(() => {
  // 初始化图表
  initProcessChart()
  initCostPieChart()
  initCostTrendChart()
  // 加载异常列表
  searchExceptions()
  // 模拟数据加载
  costLoading.value = true
  
  setTimeout(() => {
    costLoading.value = false
  }, 800)
})
</script>

<style lang="scss" scoped>
.exception-tracking {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: calc(100vh - 140px);

  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 30px;
    padding: 20px;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    border-radius: 12px;
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
    
    h2 {
      margin: 0;
      color: #fff;
      font-size: 28px;
      font-weight: bold;
    }
  }

  .process-analysis {
    background: white;
    border-radius: 8px;
    padding: 20px;
    margin-bottom: 20px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

    h3 {
      margin: 0 0 20px 0;
      color: #333;
      font-size: 18px;
      font-weight: 500;
    }

    .stats-cards {
      display: grid;
      grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
      gap: 20px;
      margin-bottom: 30px;

      .stats-card {
        padding: 20px;
        border-radius: 8px;
        color: white;
        transition: transform 0.3s ease;
        cursor: pointer;

        &:hover {
          transform: translateY(-5px);
        }

        &.blue {
          background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
        }

        &.pink {
          background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
        }

        &.green {
          background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
        }

        .stats-content {
          .stats-number {
            font-size: 28px;
            font-weight: bold;
            margin-bottom: 8px;
          }

          .stats-label {
            font-size: 14px;
            margin-bottom: 8px;
            opacity: 0.9;
          }

          .stats-trend {
            font-size: 12px;
            opacity: 0.8;
          }
        }
      }
    }

    .chart-container {
      .process-chart {
        height: 300px;
        width: 100%;
      }
    }
  }

  .exception-list {
    background: white;
    border-radius: 8px;
    padding: 20px;
    margin-bottom: 20px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

    .list-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20px;

      .header-left {
        display: flex;
        align-items: center;
        gap: 10px;

        .list-title {
          font-size: 16px;
          font-weight: 500;
          color: #333;
        }

        .total-tag {
          margin-left: 8px;
        }
      }

      .header-right {
        display: flex;
        gap: 10px;
      }
    }

    .search-filter {
      margin-bottom: 20px;
      padding: 15px;
      background-color: #f9f9f9;
      border-radius: 6px;

      .filter-form {
        display: flex;
        flex-wrap: wrap;
        gap: 10px;

        // 缩小异常类型和状态select框的宽度
        .el-form-item:nth-child(1) .el-select,
        .el-form-item:nth-child(2) .el-select {
          width: 120px;
        }
      }
    }

    .pagination-container {
      margin-top: 20px;
      display: flex;
      justify-content: flex-end;
    }
  }

  .exception-stats {
    background: white;
    border-radius: 8px;
    padding: 20px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

    .stats-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20px;

      .header-left {
        display: flex;
        align-items: center;
        gap: 10px;

        .stats-title {
          font-size: 16px;
          font-weight: 500;
          color: #333;
        }

        .report-tag {
          margin-left: 8px;
        }
      }

      .header-right {
        display: flex;
        align-items: center;
        gap: 15px;
      }

      .time-filter {
        display: flex;
        gap: 8px;
      }
    }

    .cost-analysis-charts {
      margin-bottom: 20px;

      .chart-row {
        display: grid;
        grid-template-columns: repeat(auto-fit, minmax(450px, 1fr));
        gap: 20px;
        margin-bottom: 20px;

        .chart-card {
          background: #f9f9f9;
          border-radius: 8px;
          padding: 15px;
          box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);

          .chart-title {
            font-size: 14px;
            font-weight: 500;
            color: #666;
            margin-bottom: 10px;
            text-align: center;
          }

          .cost-pie-chart,
          .cost-trend-chart {
            height: 300px;
            width: 100%;
          }
        }
      }
    }

    .stats-table {
      margin-bottom: 20px;

      .category-cell {
        display: flex;
        align-items: center;
        gap: 8px;

        .category-color {
          width: 12px;
          height: 12px;
          border-radius: 2px;
        }
      }

      .cost-value {
        font-weight: 500;
        color: #333;
      }

      .growth-up {
        color: #52c41a;
        font-weight: 500;
      }
    }
  }

  // 详情弹窗底部按钮样式
  .dialog-footer-flex {
    display: flex;
    justify-content: space-between;
    align-items: center;
    width: 100%;
  }

  .dialog-footer-left {
    flex: 1;
    text-align: left;
  }

  .dialog-footer-right {
    flex: 1;
    text-align: right;
  }

  // 时间线弹窗样式
  .timeline-card {
    margin-bottom: 10px;
    
    .timeline-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 15px;
      
      h4 {
        margin: 0;
        color: #333;
        font-size: 16px;
        font-weight: 500;
      }
    }
    
    .timeline-content {
      margin-bottom: 10px;
    }
    
    .timeline-footer {
      .remark {
        margin: 0;
        padding: 10px;
        background-color: #f5f7fa;
        border-radius: 4px;
        color: #666;
        font-size: 14px;
        border-left: 3px solid #409eff;
      }
    }
  }

  :deep(.el-timeline-item__timestamp) {
    font-weight: 500;
    color: #409eff;
  }

  :deep(.el-timeline-item__wrapper) {
    padding-left: 20px;
  }

  :deep(.el-timeline-item__tail) {
    border-left: 2px solid #e4e7ed;
  }

  :deep(.el-timeline-item__node) {
    width: 14px;
    height: 14px;
    border: 2px solid #409eff;
    background-color: #fff;
    
    &.is-success {
      border-color: #67c23a;
    }
    
    &.is-warning {
      border-color: #e6a23c;
    }
    
    &.is-danger {
      border-color: #f56c6c;
    }
  }

      .growth-down {
        color: #f5222d;
        font-weight: 500;
      }
    }

    .improvement-suggestions {
      background: #fffbe6;
      border: 1px solid #ffe58f;
      border-radius: 6px;
      padding: 15px;
      margin-top: 20px;

      .suggestions-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 15px;

        .suggestions-title {
          display: flex;
          align-items: center;
          gap: 8px;
          font-weight: 500;
          color: #d48806;

          .el-icon {
            font-size: 18px;
          }
        }
      }

      .suggestions-content {
        display: flex;
        flex-direction: column;
        gap: 15px;

        .suggestion-item {
          background: white;
          border-radius: 6px;
          padding: 12px;
          box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);

          .suggestion-title {
            font-weight: 500;
            margin-bottom: 8px;
            color: #333;
          }

          .suggestion-desc {
            font-size: 13px;
            color: #666;
            margin-bottom: 12px;
            line-height: 1.5;
          }

          .suggestion-actions {
            display: flex;
            justify-content: flex-end;
            gap: 8px;
          }
        }
      }
    }
</style>